#include "database.h"
#include "supplier.h"
#include "product.h"
#include <QDebug>

DataBase::DataBase(){
}
DataBase::DataBase(QString location){
    QFile file(location);
    if(!file.open(QIODevice::ReadOnly |QIODevice::Text))
    {
        qDebug()<<"Failed to open products file";
        return ;
    }
    else
    {
        if(!document.setContent(&file))
        {
            qDebug()<<"Failed to load products document";
            return ;
        }
        file.close();

        QDomElement root = document.firstChildElement();
        QDomElement product = root.firstChildElement();
        name=product.attribute("name");
        deadline=product.attribute("deadline").toInt();
         dailyProduction=product.attribute("dailyProduction").toInt();
        amount=product.attribute("amount").toInt();
        QDomNodeList subproducts = product.nextSiblingElement().elementsByTagName("subproduct");
        for (int i=0;i<subproducts.count();i++){
            QDomElement subproduct = subproducts.at(i).toElement();
            QString _productName = subproduct.attribute("name");
            QString _unit = subproduct.attribute("unit");
            double _quantity = subproduct.attribute("quantity").toDouble() ;
            int productId = addProduct(_productName, _unit, _quantity);

            QDomNodeList suppliers = subproduct.elementsByTagName("supplier");
            for(int k=0;k<suppliers.count();k++){
                QDomElement supplier = suppliers.at(k).toElement();
                QString _supplierName = supplier.attribute("name");
                int _dailyProduction = supplier.attribute("dailyProduction").toInt();
                double _cost = supplier.attribute("cost").toDouble();
                int _productionTime = supplier.attribute("productionTime").toInt();
                products[productId].addSupplier(_supplierName,_cost,_productionTime,_dailyProduction);
            }
        }
    }
}

Product DataBase::getProduct(int i){
    return products[i];

}
 int DataBase::addProduct(Product &fresh_product){
    products.append(fresh_product);
    return products.count()-1;
 }
int DataBase::addProduct(QString _productName, QString _unit, double _quantity){
    Product toAdd( _productName,  _unit,  _quantity);
    products.push_back(toAdd);
    return (products.count()-1);
}

bool DataBase::removeProduct(int i){
    products.remove(i);
    return true;
}
QString DataBase::getName(){
    return name;
}

int DataBase::getDeadline(){
    return deadline;
}

int DataBase::getAmount(){
    return amount;
}
int DataBase::countProducts(){
    return products.count();

}
void DataBase::clearProducts(){
    products.clear();
}
int DataBase::getQuantityAvalaiblePerDay(){
    return dailyProduction;
}
